package com.itheima.app.interceptor;

import com.itheima.app.manager.UserManager;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private UserManager userManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.取出请求头中的token
        String token = request.getHeader("Authorization");
        //2.根据token获取user
        User user = userManager.findUserByToken(token);
        //3.判断是否被封禁登录
        if (stringRedisTemplate.hasKey(ConstantUtil.FREEZE_LOGIN + user.getId())) {
            response.setStatus(401);
            return false;
        }
        if (user == null) {
            response.setStatus(401);
            return false;
        }
        UserHolder.set(user);
        return true;
    }
    // 处理响应
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
